<template>
    <el-container>
        <el-main>
            <el-form ref="productForm" :model="form" label-width="90px">
                <div style="display: flex">
                    <div>
                        <el-form-item label="活动名称" prop="name" :rules="{ required: true, message: '请输入团购名称', trigger: 'blur' }">
                            <el-input placeholder="请输入团购名称" style="width: 430px" v-model="form.name" />
                        </el-form-item>
                        <el-form-item label="活动说明" prop="subTitle">
                            <el-input placeholder="请输入团购副标题" style="width: 430px" v-model="form.subTitle" />
                        </el-form-item>
                        <el-form-item label="起止日期" prop="endDate" :rules="{ required: true, message: '请选择活动时间', trigger: 'blur' }">
                            <el-date-picker v-model="form.endDate" type="datetimerange" style="width: 430px" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
                            </el-date-picker>
                        </el-form-item>
                    </div>
                </div>
                <div style="display: flex">
                    <el-form-item label="团购价" prop="price" :rules="{ required: true, message: '请输入团购价', trigger: 'blur' }">
                        <el-input style="width: 170px" v-model="form.price" placeholder="请输入团购价" />
                    </el-form-item>
                  <el-form-item label="成团人数">
                    <el-select v-model="form.groupNum" style="width: 170px" clearable filterable :filter-method="queryDistribution" placeholder="请选择成团人数">
                      <el-option v-for="item in numberPeopleOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>

                  <el-form-item prop="robotNum" label-width="150px" class="foregroundDisplay" label="发起人要求必需购买" style="width: 185px">
                    <el-checkbox  v-model="form.robotNum" size="medium"></el-checkbox>
                  </el-form-item>
                </div>
                <div style="display:flex">
                  <el-form-item label="奖励金" prop="point" :rules="{ required: true, message: '请输入奖励金', trigger: 'blur' }">
                    <el-input style="width: 170px" v-model="form.point" placeholder="请输入奖励金额" />
                  </el-form-item>
                  <el-form-item label="兑换券" prop="matchPoint" :rules="{ required: true, message: '请输入兑换券', trigger: 'blur' }">
                    <el-input style="width: 170px" v-model="form.matchPoint" placeholder="请输入兑换券" />
                  </el-form-item>
                  <el-form-item label="购物券" prop="cardPoint" :rules="{ required: true, message: '请输入购物券', trigger: 'blur' }">
                    <el-input style="width: 170px" v-model="form.cardPoint" placeholder="请输入购物券" />
                  </el-form-item>
                </div>
                <div style="display:flex">
                  <el-form-item label="每人限购" prop="limitNum" :rules="{ required: true, message: '请输入每人限购', trigger: 'blur' }">
                    <el-input style="width: 170px;" v-model="form.limitNum" placeholder="0代表无限" />
                  </el-form-item>
                  <el-form-item label="分销策略">
                    <el-select style="width: 170px;" v-model="form.distributionId" clearable filterable :filter-method="queryDistribution" placeholder="请选择分销策略">
                      <el-option v-for="item in disOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="开启抽奖">
                    <div style="width:40px">
                      <el-switch @change="switchClick" v-model="switchValue" active-color="#13ce66" inactive-color="#ff4949">
                      </el-switch>
                    </div>
                  </el-form-item>
                  <div  v-if="switchValue == false" style="width: 130px"></div>
                  <el-form-item label="抽奖次数"  v-if="switchValue == true" >
                    <el-input style="width: 40px;" v-model="form.luckyNum" placeholder="请输入抽奖次数" />
                  </el-form-item>
                </div>

                <el-tabs v-model="activeTab">
                  <el-tab-pane label="活动商品" name="produlist">
                    <el-row style="display: flex;  position: relative;margin-left: 90px">
              <span class="el-icon-plus" style="position: absolute; top: 69px;left: -25px; color: #409EFF;"
                    @click="addProduct"/>
                      <el-col :span="16">
                        <el-table
                          :data="productList"
                          border
                          stripe
                          style="width: 100%;"
                        >
                          <el-table-column
                            label="商品名称"
                            min-width="320"
                          >
                            <template slot-scope="scope">
                              <el-select style="width: 100%" value-key="id" v-model="scope.row.name" filterable
                                         @focus="selectIndex(scope)"    placeholder="请选择" @change="selectClick(scope)" :filter-method="productMethod">
                                <el-option
                                  v-for="(item,index) in listForm"
                                  :key="item.id"
                                  :label="item.name"
                                  :value="item"
                                >
                                </el-option>
                                <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                                  <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                                  <div class="elOption" @click="toAddProduct">搜索商品</div>
                                </div>
                                <div style="height: 30px"></div>
                              </el-select>
                            </template>
                          </el-table-column>
                          <el-table-column
                            label="商品图片"
                            width="80"
                            align="center"
                            prop="thumbnail"
                          >
                            <template slot-scope="{row}">
                              <img :src="row.thumbnail" v-if="row.thumbnail!=''" style="width: 50px;height: 50px">
                            </template>
                          </el-table-column>
                          <el-table-column
                            label="规格"
                            min-width="220"
                          >
                            <template slot-scope="{row}">
                              <span>{{row.spec}}</span>
                              <!-- <el-input v-model="row.spec"/> -->
                            </template>
                          </el-table-column>
                          <el-table-column
                            label="单位"
                            width="120"
                          >
                            <template slot-scope="{row}">
                              <!-- <el-input v-model="row.unit"/> -->
                              <span>{{row.unit}}</span>
                            </template>
                          </el-table-column>
                          <el-table-column
                            align="center"
                            label="操作"
                            width="80"
                          >
                            <template v-if="!row.isList" slot-scope="{row}">
                              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                                <a @click="delProduct(row)">
                                  <i style="color: #F56C6C" class="el-icon-delete"/>
                                </a>
                              </el-tooltip>
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                    <el-tab-pane label="抽奖期数" name="luckDraw"  v-if="switchValue == false">
                        <div style=" display: flex; justify-content: space-between; margin-bottom: 10px; width: 600px;">
                            <div style="display: flex;justify-content: flex-start">
                            </div>
                            <div style="display: flex;justify-content: flex-end">
                                <el-button size="small" type="primary" @click="toAddluckDraw">新增
                                </el-button>
                            </div>
                        </div>
                        <div style="width:600px">
                            <el-table style="width:100%" :data="luckDrawList" border stripe>
                                <el-table-column label="期数" type="index" width="50" align="center" />
                                <el-table-column label="红包">
                                    <template slot-scope="{row}">
                                        <el-input type="number" v-model="row.point" placeholder="请输入红包金额" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="兑换券">
                                    <template slot-scope="{row}">
                                        <el-input type="number" v-model="row.matchPoint" placeholder="请输入兑换券数量" />
                                    </template>
                                </el-table-column>
                              <el-table-column label="购物券">
                                <template slot-scope="{row}">
                                  <el-input type="number" v-model="row.cardPoint" placeholder="请输入购物券数量" />
                                </template>
                              </el-table-column>

                                 <el-table-column label="操作" align="center" fixed="right" width="80">
                                    <template slot-scope="scope">
                                        <a style="" @click="delLuckDraw(scope.$index)">
                                            <i style="color: #F56C6C" class="el-icon-delete" />
                                        </a>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <el-button style="margin-top:20px" type="primary" :loading="clicked" @click="editProduct('productForm')">
                    &nbsp&nbsp完 成&nbsp&nbsp
                </el-button>
            </el-form>
        </el-main>
        <el-dialog title="新增商品" :visible.sync="procuctVisible" width="950px" v-el-drag-dialog :before-close="productClose">
            <div style="height: 65vh;overflow: auto;position: relative;">
                <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
            </div>
        </el-dialog>
        <el-dialog title="搜索商品" :visible.sync="orderVisible" width="950px" v-el-drag-dialog :before-close="orderClose">
            <div style="position: relative;">
                <productTable ref="productList" @doubleClick="doubleClick" @addClick="addClick"></productTable>
            </div>
        </el-dialog>
    </el-container>
</template>

<script>
import productAdd from "@/views/product/add";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import productTable from "./components//productList";
import { EventBus } from "@/api/eventBus";
import SingleUpload from "@/components/Upload/singleUpload";
import { list } from "@/api/product";
import permission from "@/directive/permission";
import { list as distributionList } from "@/api/distribution.js";
import utils from "@/utils/utils";
import {
    find,
    update,
} from "@/api/groupBuy";

export default {
    name: "multiPersonGroup-edit",
    directives: { elDragDialog, permission },
    data() {
        return {
            activeTab: "produlist",
            query: { keyword: "" },
            pageSize: 10,
            pageNum: 1,
            total: 0,
            paginationShow: true,
            marketForm: [],
            payLoads: "",
            productTitle: "",
            productForm: [],
            disOptions: [],
            numberPeopleOptions: [
                { name: "2人团", id: "2" },
                { name: "3人团", id: "3" },
                { name: "4人团", id: "4" },
                { name: "5人团", id: "5" },
                { name: "6人团", id: "6" },
                { name: "7人团", id: "7" },
            ],
            form: {
                id: "",
                type: 2,
                thumbnail: "",
                robotNum: 0,
                subTitle: "",
                duration: 0,
                endDate: [],
                point: 0,
                name: "",
                beginDate: "",
                groupNum: "2",
                periodNum: "",
                orderNum: 0,
                price: "",
                marketPrice: 0,
                isShow: "",
                matchPoint: "",
                distributionId: "",
                limitNum: "",
                luckyNum: 0,
                cardPoint:''
            },
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() + 86400000 < Date.now();
                },
            },
            article: {
                productMeta: {
                    images: [],
                    video: "",
                    label: "",
                },
                content: "",
            },
            index: "",
            orderVisible: false,
            productType: "order",
            procuctVisible: false,
            clicked: false,
            listForm: [],
            productList: [
                {
                    name: "",
                    productId: "",
                    quantity: 1,
                    spec: "",
                    thumbnail: "",
                    unit: "",
                },
            ],
            luckDrawList: [],
            activeName: "produlist",
            switchValue: false,
        };
    },
    watch: {
        // 路由地址不变的情况下,如果id变化则重新获取数据
        $route(newVal, oldVal) {
            console.log(newVal.query.id);
            console.log(this.form.id);
            if (
                newVal.name == "sevengroupBuy-edit" &&
                newVal.query.id != this.form.id
            ) {
                this.getData();
            }
        },
    },
    activated() {
        this.payLoads = new Date().getTime();
    },
    created() {
        this.getData();
        this.loadProduct('')
        this.queryDistribution("");
    },
    components: {
        productAdd,
        productTable,
        SingleUpload,
    },
    methods: {
      selectIndex(data){
        this.index=data.$index
      },
      productClose() {
        this.procuctVisible = false;
      },
      toAddProduct(){
        this.orderVisible = true;
      },
      orderClose() {
        this.orderVisible = false;
        this.$refs.productList.cancelClick();
      },
      toSearchProduct(){
        this.procuctVisible = true;
      },
      saveProduct(data) {
        this.listForm.splice(0, 0, data);
        this.procuctVisible = false;
      },
      doubleClick(val) {
        if (this.productList.length==1&&this.productList[0].name==''){
          this.productList[0].productId=val.id
          this.productList[0].name=val.name
          this.productList[0].quantity=1
          this.productList[0].thumbnail=val.thumbnail
          this.productList[0].spec=val.spec1 + val.spec2
          this.productList[0].unit=val.unit
        }else if (this.productList[this.productList.length-1].name==''){
          this.productList[this.productList.length-1].productId=val.id
          this.productList[this.productList.length-1].name=val.name
          this.productList[this.productList.length-1].quantity=1
          this.productList[this.productList.length-1].thumbnail=val.thumbnail
          this.productList[this.productList.length-1].spec=val.spec1 + val.spec2
          this.productList[this.productList.length-1].unit=val.unit
        }else{
          this.productList[this.index].productId=val.id
          this.productList[this.index].name=val.name
          this.productList[this.index].quantity=1
          this.productList[this.index].thumbnail=val.thumbnail
          this.productList[this.index].spec=val.spec1 + val.spec2
          this.productList[this.index].unit=val.unit
        }
        this.searchSame()
        this.orderVisible=false
        this.setAddClickHeight()
      },
      searchSame(){
        var newList={}
        newList=this.productList[this.productList.length-1]
        if (this.productList.length>1){
          for (var i=0;i<this.productList.length-1;i++){
            if (this.productList[i].productId===newList.productId){

              this.productList[i].quantity=this.productList[i].quantity+1
              this.productList.pop()
            }
          }
        }
        this.productList = this.productList.filter(item => {
          return item.name!=''
        })
      },
      addClick(data) {
        var _this = this
        if (this.productList.length==1&&this.productList[0].name==''){
          var list=[]
          data.forEach(item=>{
            var goodsDetails = {
              productId: item.id,
              name: item.name,
              quantity:1,
              thumbnail:item.thumbnail,
              spec: item.spec1 + item.spec2,
              unit: item.unit
            }
            list.push(goodsDetails)
          })
          _this.productList=list
          _this.productList[0].quantity=1
        }else{
          data.forEach(item=>{
            var goodsDetails = {
              productId: item.id,
              name: item.name,
              quantity:1,
              thumbnail:item.thumbnail,
              spec: item.spec1 + item.spec2,
              unit: item.unit
            };
            _this.productList.push(goodsDetails)
          });
        }
        this.orderVisible=false
        this.setAddClickHeight()
        this.searchSame()
      },

      setAddClickHeight() {
        setTimeout(() => {
          // 获取表头的高度
          const tableTopHeight = document.querySelector('.el-table__header-wrapper').offsetHeight
          // 获取一行表格高度
          const tableHeight = document.querySelector('.el-table__row').offsetHeight
          // 获取添加按钮样式
          const addClickStyle = document.querySelector('.el-icon-plus')
          // 获取添加按钮高度
          const addClickHeight = addClickStyle.offsetHeight
          // 设置添加按钮的位置
          const moveHeight = tableTopHeight + ((this.productList.length - 1) * tableHeight) + ((tableHeight - addClickHeight) / 2)
          console.log(tableTopHeight, 'tableTopHeight')
          console.log(tableHeight, 'tableHeight')
          console.log(moveHeight, 'moveHeight')
          addClickStyle.style.top = moveHeight + 'px'
        }, 100)
      },
      addProduct(){
        var products={
          name:'',
          quantity:'',
          spec:'',
          thumbnail:'',
          unit:''
        }
        this.productList.push(products)
        this.setAddClickHeight()
      },
      selectClick(data) {
        this.productList[data.$index].spec = data.row.name.spec1
        this.productList[data.$index].productId = data.row.name.id
        this.productList[data.$index].quantity = 1
        this.productList[data.$index].thumbnail = data.row.name.thumbnail
        this.productList[data.$index].unit = data.row.name.unit
        this.productList[data.$index].name = data.row.name.name
        this.searchSame()
      },
        getData() {
            this.form.id = this.$route.query.id;
            this.form.endDate = [];
            find(this.form.id).then((res) => {
                this.form.cardPoint = res.data.groupBuy.cardPoint;
                this.form.isShow = res.data.groupBuy.isShow;
                this.form.name = res.data.groupBuy.name;
                this.form.distributionId = res.data.groupBuy.distributionId;
                this.form.type = res.data.groupBuy.type;
                this.form.duration = res.data.groupBuy.duration;
                if(res.data.groupBuy.robotNum == 0){
                  this.form.robotNum = false
                }else {
                  this.form.robotNum = true
                }
                this.form.subTitle = res.data.groupBuy.subTitle;
                this.form.periodNum = res.data.groupBuy.periodNum;
                this.form.thumbnail = res.data.groupBuy.thumbnail;
                this.form.endDate.push(res.data.groupBuy.beginDate);
                this.form.endDate.push(res.data.groupBuy.endDate);
                this.form.limitNum = res.data.groupBuy.limitNum;
                this.form.point = res.data.groupBuy.point / 100;
                this.form.matchPoint = res.data.groupBuy.matchPoint;
                if (res.data.groupBuy.groupNum != null) {
                    this.form.groupNum = res.data.groupBuy.groupNum.toString();
                }
                this.form.orderNum = res.data.groupBuy.orderNum;
                this.form.price = res.data.groupBuy.price;
                this.form.marketPrice = res.data.groupBuy.marketPrice;
                this.productList = res.data.groupBuy.itemList;
                this.article = res.data.groupBuy.article;
                this.form.luckyNum = res.data.groupBuy.luckyNum;
                if(this.form.luckyNum > 0){
                     this.switchValue= true
                }
                res.data.groupBuy.periodList.forEach(item=>{
                  item.point = item.point/100
                })
                this.luckDrawList = res.data.groupBuy.periodList;
                this.setAddClickHeight();
            });
        },
        productMethod(query) {
            this.loadProduct(query);
        },
        delProduct(row) {
            var index = this.productList.indexOf(row);
            if (index !== -1) {
                this.productList.splice(index, 1);
            }

            this.setAddClickHeight();
        },
        loadProduct(query) {
            var param = new URLSearchParams();
            param.append("name", query);
            list(param).then((res) => {
                this.listForm = res.data.data;
            });
        },

        editProduct(form) {
            var _this = this;
            this.$refs[form].validate((valid) => {
                if (valid) {
                    // 校验表单
                    this.clicked = true;
                    let newDate = this.form.endDate;
                    if (newDate.length > 0) {
                        this.form.beginDate = newDate[0];
                        this.form.endDate = newDate[1];
                    }
                    this.productList = this.productList.filter((item) => {
                        return item.name != "";
                    });
                    if (_this.luckDrawList.length > 0) {
                        _this.luckDrawList.forEach(function (item, index) {
                            item.periodNum = index + 1;
                        });
                    }

                    if(this.form.robotNum == true){
                      this.form.robotNum = 1
                    }else {
                      this.form.robotNum = 0
                    }
                    if(this.luckDrawList.length >0 ){
                      this.luckDrawList.forEach(item=>{
                        item.point = item.point * 100
                      })
                    }
                    var product = {
                        id: this.form.id,
                        distributionId: this.form.distributionId,
                        type: this.form.type,
                        subTitle: this.form.subTitle,
                        endDate: this.form.endDate,
                        beginDate: this.form.beginDate,
                        periodNum: 0,
                        cardPoint: this.form.cardPoint,
                        robotNum: this.form.robotNum,
                        duration: this.form.duration,
                        thumbnail: this.form.thumbnail,
                        point: this.form.point * 100,
                        matchPoint: this.form.matchPoint,
                        groupNum: this.form.groupNum,
                        status: 0,
                        name: this.form.name,
                        orderNum: this.form.orderNum,
                        isShow: this.form.isShow,
                        price: this.form.price,
                        marketPrice: this.form.marketPrice,
                        itemList: this.productList,
                        limitNum: this.form.limitNum,
                        luckyNum: this.form.luckyNum,
                        periodList: this.luckDrawList,
                        article: {
                            productMeta: {},
                            content: this.article.content,
                        },
                    };
                    product.article.productMeta = this.article.productMeta;
                    console.log(product);
                    update(product)
                        .then((res) => {
                            this.clicked = false;
                            EventBus.$emit("multiPersonGroup-edit", res.data);
                            this.$store
                                .dispatch("tagsView/delView", this.$route)
                                .then(({ visitedViews }) => {
                                    this.$router.push({
                                        path: "/multiPersonGroup/list",
                                    });
                                }); // 关闭当前tab回到列表
                        })
                        .catch((error) => {
                            this.clicked = false;
                        });
                }
            });
        },
        queryClick() {
            this.marketClick();
        },
        toAddluckDraw() {
            var product = {
                point: "",
                matchPoint: "",
                periodNum: "",
                groupNum: 0,
                buyNum: 0,
            };
            this.luckDrawList.push(product);
        },
        switchClick(value) {
            if (value == false) {
                this.form.luckyNum = 0;
            }
        },
        delLuckDraw(index){
            console.log(index)
            this.luckDrawList.splice(index,1)
        },
      queryDistribution(query) {
        const params = new URLSearchParams();
        params.append("pageNum", 1);
        params.append("pageSize", 50);
        params.append("name", query);
        distributionList(params)
          .then((res) => {
            this.disOptions = res.data.data;
            console.log(res, "分销");
          })
          .catch((err) => {
            console.log(err);
          });
      },
    },
};
</script>

<style scoped>
/deep/el-upload-list__item is-success {
    width: 90px;
}
.photo-content {
    width: 100%;
    display: flex;
    align-items: flex-end;
    border-top: 1px #eee solid;
    margin-bottom: 20px;
    margin-top: 10px;
}
/deep/.el-input__inner {
    padding: 0 5px;
}
/deep/.el-upload__tip {
    display: none;
}
/deep/.el-upload-list--picture {
    position: absolute;
    width: 110px;
}
.elOption1 {
    background-color: #409eff;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px;
}
.elOption {
    background-color: #909399;
    color: white;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px;
}
/deep/ .el-upload--picture-card {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
    text-align: center;
}
</style>
